package com.haitaoit.chengquan.ui.equipment.activity;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.utils.NetworkMonitor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import cn.bluemobi.dylan.photoview.library.PhotoView;
import cn.bluemobi.dylan.photoview.library.PhotoViewAttacher;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.haitaoit.chengquan.R.id.photoview;

/**
 * Created by 赵航 on 2017/10/17.
 */

public class ShowPictureActivity extends AppCompatActivity {

    private PhotoView      mPhotoView;
    private String         mUri;
    private ProgressDialog mDialog;
    private TextView       mSave;
    private byte[]         mPicture_bt;
    private Bitmap         mBitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.showpictureactivity);
        mPhotoView = (PhotoView) findViewById(photoview);
        View viewById = findViewById(R.id.linelayout);
        mSave = (TextView) findViewById(R.id.seave);
        mDialog = new ProgressDialog(this);
        mDialog.setMessage("加载中，请稍等....");
        mDialog.setCancelable(false);

        Intent intent = getIntent();
        mUri = intent.getStringExtra("image_uri");
        if (mUri != null) {
            if (hasNetWork()) {
                mDialog.show();
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(mUri)
                        .build();

                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ShowPictureActivity.this, "图片加载失败,请稍后再试", Toast.LENGTH_SHORT).show();
                                mDialog.dismiss();
                            }
                        });


                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        mPicture_bt = response.body().bytes();
                        mBitmap = BitmapFactory.decodeByteArray(mPicture_bt, 0, mPicture_bt.length);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //通过imageview，设置图片
                                mPhotoView.setImageBitmap(mBitmap);

                                mDialog.dismiss();
                            }
                        });

                    }
                });
            }

        }
        //保存图片
        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取内部存储状态
                String state = Environment.getExternalStorageState();
                //如果状态不是mounted，无法读写
                if (!state.equals(Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(ShowPictureActivity.this, "请检查内存卡是否正常", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!mDialog.isShowing()) {
                    mDialog.setMessage("正在保存中，请稍等....");
                    mDialog.show();
                }
                String fileName1 = UUID.randomUUID().toString();
                String dir = Environment.getExternalStorageDirectory().getAbsolutePath();
                try {
                    //保存到本地
                    File file = new File(dir, fileName1 + ".jpg");
                    FileOutputStream out = new FileOutputStream(file);
                    mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                    mDialog.dismiss();
                    Toast.makeText(ShowPictureActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    mDialog.dismiss();
                    Toast.makeText(ShowPictureActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }

            }
        });

        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mPhotoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
              finish();
            }
        });


    }

    protected boolean hasNetWork() {
        boolean connected = NetworkMonitor.isConnected(this);
        if (!connected) {
            Toast.makeText(this, "无网络连接,请稍后再试", Toast.LENGTH_SHORT).show();
        }
        return connected;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }
}
